package com.example.taiyang.guidepro0503.mode;

import com.example.taiyang.guidepro0503.bean.WeatherResult;
import com.example.taiyang.guidepro0503.iface.WeatherInface;
import com.example.taiyang.guidepro0503.listener.WeatherListener;
import com.example.taiyang.guidepro0503.service.WeatherService;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * Created by taiyang on 2017/4/21.
 */

public class WeatherMode implements WeatherInface{
    private static final String BASE_URL="http://www.weather.com.cn/data/";
    private WeatherService service;
    private Retrofit retrofit;
    @Override
    public void getWeather(String cityNumber, final WeatherListener listener) {
        //步骤1：创建Retrofit对象
        retrofit=new Retrofit.Builder()
                .baseUrl(BASE_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .build();

        //步骤2：创建API请求
        service=retrofit.create(WeatherService.class);
        Call<WeatherResult> call=service.getReault(cityNumber);

        //步骤3：发送请求并处理结果
        call.enqueue(new Callback<WeatherResult>() {
            @Override
            public void onResponse(Call<WeatherResult> call, Response<WeatherResult> response) {
                if (response.isSuccessful() && response.body()!=null){
                    listener.onResponse(response.body().getWeatherInfo());
                }
            }

            @Override
            public void onFailure(Call<WeatherResult> call, Throwable t) {
                listener.onFailure(t.toString());
            }
        });
    }
}
